﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace filerename
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void submit_Click(object sender, EventArgs e)
        {
            TextBox text = filepath;
            TextBox subString = oldString;
            TextBox newSubString = newstring;

            string filePath = text.Text;
            string subName = subString.Text;
            string newSub = newSubString.Text;

            DirectoryInfo folder = new DirectoryInfo(filePath);

            renameDir(subName, newSub, folder);
            string msg = "";
            msg +=renameFile(subName, newSub, folder);
            groupBox1.Text = msg;
            MessageBox.Show("操作完成");
        }
        private void renameDir(string subName, string newSub, DirectoryInfo folder)
        {
            //子目录
            DirectoryInfo[] dirs = folder.GetDirectories();
            foreach (DirectoryInfo dir in dirs)
            {
                renameFile(subName, newSub, dir);
                string path = dir.FullName;
                string pathname = dir.Name;
                string newDirName = "";
                
                if (subName.Length > 0 && dir.Name.IndexOf(subName) != -1)
                {
                    newDirName = dir.Name.Replace(subName, newSub);//替换文件名称
                    Directory.Move(dir.FullName, folder.FullName + "\\" + newDirName);//重命名
                }

            }
        }

        private string renameFile(string subName,string newSub, DirectoryInfo folder)
        {
            renameDir(subName, newSub, folder);//相互调用 如果还有
            string groupBox = "";
            foreach (FileInfo file in folder.GetFiles())
            {
                string newFileName = "";
                if (subName.Length > 0 && file.Name.IndexOf(subName) != -1)
                {
                    newFileName = file.Name.Replace(subName, newSub);//替换文件名称
                    File.Move(file.FullName, file.DirectoryName + "\\" + newFileName);//重命名
                    groupBox += file.Name + "\r\n";
                }

            }
            return groupBox;
        }
        
    }
}
